import { AppDispatch } from '..';
import { getSearchResultAPI, getSuggestsAPI } from '@/api/search';
import { SearchActionType } from '../reducer/search';

/** 获取搜索建议 */
export const getSuggestsAction = (keyword: string) => {
  return async (dispatch: AppDispatch) => {
    const res = await getSuggestsAPI(keyword);
    dispatch({ type: 'search/saveList', payload: res.data.options });
  };
};

/** 清除搜索建议 */
export const clearSuggestsAction = (): SearchActionType => {
  return {
    type: 'search/clearList',
  };
};

export const saveHistoriesAction = (payload: string): SearchActionType => {
  return {
    type: 'search/saveHistories',
    payload,
  };
};

export const clearHistoriesAction = (): SearchActionType => {
  return {
    type: 'search/clearHistories',
  };
};

export const getResultsAction = (keyword: string, page = 1, per_page = 10) => {
  return async (dispatch: AppDispatch) => {
    const res = await getSearchResultAPI({ keyword, page, per_page });
    dispatch({ type: 'search/saveResults', payload: res.data.results });
  };
};

export const clearResultsAction = (): SearchActionType => ({ type: 'search/clearResults' });
